<template>
  <div class="login-container">
    <!-- 背景动画粒子 -->
    <div class="particles">
      <div v-for="i in 50" :key="i" class="particle" :style="getParticleStyle(i)"></div>
    </div>

    <!-- 动态背景 -->
    <div class="animated-bg">
      <div class="bg-shape shape-1"></div>
      <div class="bg-shape shape-2"></div>
      <div class="bg-shape shape-3"></div>
      <div class="bg-shape shape-4"></div>
    </div>

    <!-- 欢迎文字 -->
    <div class="welcome-text">
      <h2 class="welcome-title">{{ isRegisterMode ? '欢迎加入' : '欢迎回来' }}</h2>
      <p class="welcome-desc">{{ isRegisterMode ? '开始您的API之旅' : '开启您的API之旅' }}</p>
    </div>

    <!-- 登录表单 -->
    <div class="login-box" ref="loginBox">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo-container">
          <div class="logo-circle">
            <i class="logo-icon">
              <img class="w-100% h-100%" src="@/assets/logo.png" alt="">
            </i>
          </div>
        </div>
        <h1 class="title">APIHub</h1>
        <p class="subtitle">专业的接口文档管理与团队协作平台</p>
      </div>

      <!-- 登录/注册表单 -->
      <form class="login-form" @submit.prevent="handleSubmit">
        <div class="input-group">
          <div class="input-wrapper">
            <input v-model="formData.username" type="text" id="username" class="input-field" required>
            <label for="username" class="input-label">
              <i class="input-icon">👤</i>
              用户名
            </label>
            <div class="input-line"></div>
          </div>
        </div>

        <div class="input-group">
          <div class="input-wrapper" v-if="isRegisterMode">
            <input v-model="formData.nickname" type="text" id="username" class="input-field" required>
            <label for="username" class="input-label">
              <i class="input-icon">🪪 </i>
              昵称
            </label>
            <div class="input-line"></div>
          </div>
        </div>

        <div class="input-group">
          <div class="input-wrapper">
            <input v-model="formData.password" type="password" id="password" class="input-field" required>
            <label for="password" class="input-label">
              <i class="input-icon">🔑</i>
              密码
            </label>
            <div class="input-line"></div>
          </div>
        </div>

        <div class="input-group" v-if="isRegisterMode">
          <div class="input-wrapper">
            <input v-model="formData.confirmPassword" type="password" id="confirmPassword" class="input-field" required>
            <label for="confirmPassword" class="input-label">
              <i class="input-icon">✅</i>
              确认密码
            </label>
            <div class="input-line"></div>
          </div>
        </div>

        <!-- 验证码区域 -->
        <div class="input-group" v-if="isRegisterMode">
          <div class="input-wrapper captcha-wrapper">
            <input v-model="formData.captcha" type="text" id="captcha" class="input-field captcha-input" required>
            <label for="captcha" class="input-label">
              <i class="input-icon">🛡️</i>
              验证码
            </label>
            <div class="input-line"></div>
            <div class="captcha-code" @click="refreshCaptcha">
              {{ captchaCode }}
            </div>
          </div>
        </div>

        <div class="form-options">
          <div class="register-section">
            <span class="register-text">{{ isRegisterMode ? '已有账号？' : '还没有账号？' }}</span>
            <a href="#" class="register-link" @click.prevent="toggleMode">
              {{ isRegisterMode ? '立即登录' : '立即注册' }}
            </a>
          </div>
          <a href="#" class="forgot-link" v-if="!isRegisterMode">忘记密码？</a>
        </div>

        <button type="submit" class="login-btn" :class="{ loading: isLoading }">
          <span class="btn-text">
            {{ isLoading ? (isRegisterMode ? '注册中...' : '登录中...') : (isRegisterMode ? '立即注册' : '登录系统') }}
          </span>
          <div class="btn-loader" v-if="isLoading">
            <div class="spinner"></div>
          </div>
        </button>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from "@/store/modules/user.ts";
import { handlePwdLogin, handleRegisterApi } from '@/common/apis/users';

const router = useRouter();
const loginBox = ref(null);
const isLoading = ref(false);
const userStore = useUserStore();
const isRegisterMode = ref(false);
const captchaCode = ref('');

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  nickname: '',
});

// 生成验证码
const generateCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  captchaCode.value = result;
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
};

// 切换登录/注册模式
const toggleMode = () => {
  isRegisterMode.value = !isRegisterMode.value;
  // 清空表单数据
  Object.assign(formData, {
    username: '',
    password: '',
    nickname: '',
    confirmPassword: '',
    captcha: '',
  });
  // 如果是注册模式，生成验证码
  if (isRegisterMode.value) {
    generateCaptcha();
  }
};

// 生成粒子样式
const getParticleStyle = (index: number) => {
  const size = Math.random() * 4 + 2;
  const x = Math.random() * 100;
  const y = Math.random() * 100;
  const delay = Math.random() * 20;
  const duration = Math.random() * 10 + 10;

  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${x}%`,
    top: `${y}%`,
    animationDelay: `${delay}s`,
    animationDuration: `${duration}s`
  };
};

onMounted(() => {
  // 触发登录框动画
  setTimeout(() => {
    if (loginBox.value) {
      loginBox.value.classList.add('animate');
    }
  }, 300);
});

const handleSubmit = async () => {
  if (isRegisterMode.value) {
    await handleRegister();
  } else {
    await handleLogin();
  }
};

const handleLogin = async () => {
  if (!formData.username || !formData.password) {
    return;
  }
  isLoading.value = true;
  const _params = { username: formData.username, password: formData.password };
  // 登录请求
  try {
    const { data } = await handlePwdLogin(_params);
    userStore.setToken(data.token);
    // 登录成功后跳转到首页，清空所有路由参数
    router.push({ path: '/', replace: true });
  } catch (error) {

  } finally {
    isLoading.value = false;
  }
};

const handleRegister = async () => {
  // 验证表单
  if (!formData.username || !formData.nickname || !formData.password || !formData.confirmPassword || !formData.captcha) {
    return;
  }

  // 验证密码确认
  if (formData.password !== formData.confirmPassword) {
    ElMessage({
      message: '两次输入密码不一致',
      type: 'warning',
    });
    return;
  }

  // 验证验证码
  if (formData.captcha.toLowerCase() !== captchaCode.value.toLowerCase()) {
    ElMessage({
      message: '验证码错误',
      type: 'warning',
    });
    refreshCaptcha();
    return;
  }

  isLoading.value = true;
  // 这里添加注册API调用
  try {
    const res = await handleRegisterApi(formData);
    // 模拟注册成功
    ElMessage.success({ message: `${res.message}` });
    toggleMode(); // 切换回登录模式
  } catch (error) {
    console.error('注册失败:', error);
  } finally {
    isLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
// 变量定义
@primary-color: #6366f1;
@primary-light: #818cf8;
@primary-dark: #4f46e5;
@text-color: #1f2937;
@text-light: #6b7280;
@white: #ffffff;
@shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
@shadow-lg: 0 20px 40px rgba(0, 0, 0, 0.15);

.login-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: flex-end; // 改为右对齐

  // 粒子动画
  .particles {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: 1;

    .particle {
      position: absolute;
      background: rgba(255, 255, 255, 0.6);
      border-radius: 50%;
      animation: float 20s infinite linear;
      pointer-events: none;

      @keyframes float {
        0% {
          transform: translateY(100vh) rotate(0deg);
          opacity: 0;
        }

        10% {
          opacity: 1;
        }

        90% {
          opacity: 1;
        }

        100% {
          transform: translateY(-100px) rotate(360deg);
          opacity: 0;
        }
      }
    }
  }

  // 动态背景形状
  .animated-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;

    .bg-shape {
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      animation: float-shape 15s infinite ease-in-out;

      &.shape-1 {
        width: 200px;
        height: 200px;
        top: 10%;
        left: 10%;
        animation-delay: 0s;
      }

      &.shape-2 {
        width: 150px;
        height: 150px;
        top: 60%;
        right: 15%;
        animation-delay: 3s;
      }

      &.shape-3 {
        width: 100px;
        height: 100px;
        bottom: 20%;
        left: 20%;
        animation-delay: 6s;
      }

      &.shape-4 {
        width: 120px;
        height: 120px;
        top: 30%;
        right: 30%;
        animation-delay: 9s;
      }

      @keyframes float-shape {

        0%,
        100% {
          transform: translateY(0px) rotate(0deg);
        }

        33% {
          transform: translateY(-30px) rotate(120deg);
        }

        66% {
          transform: translateY(20px) rotate(240deg);
        }
      }
    }
  }

  // 欢迎文字
  .welcome-text {
    position: absolute;
    left: 20%;
    top: 50%;
    transform: translateY(-50%);
    z-index: 5;
    color: @white;
    text-align: left;

    .welcome-title {
      font-size: 48px;
      font-weight: 700;
      margin: 0 0 16px 0;
      opacity: 0;
      animation: slideInLeft 1s ease-out 0.5s forwards;
    }

    .welcome-desc {
      font-size: 20px;
      margin: 0;
      opacity: 0;
      animation: slideInLeft 1s ease-out 0.8s forwards;
    }

    @keyframes slideInLeft {
      from {
        opacity: 0;
        transform: translateX(-50px);
      }

      to {
        opacity: 1;
        transform: translateX(0);
      }
    }
  }

  // 登录框
  .login-box {
    position: relative;
    z-index: 10;
    width: 420px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    padding: 40px;
    box-shadow: @shadow-lg;
    border: 1px solid rgba(255, 255, 255, 0.2);
    transform: translateY(50px) scale(0.9);
    opacity: 0;
    transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);
    margin-right: 8%; // 添加右边距，让登录框更靠右

    &.animate {
      transform: translateY(0) scale(1);
      opacity: 1;
    }

    // Logo区域
    .logo-section {
      text-align: center;
      margin-bottom: 40px;

      .logo-container {
        margin-bottom: 20px;

        .logo-circle {
          width: 80px;
          height: 80px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 0 auto;
          animation: pulse 2s infinite;

          .logo-icon {
            font-size: 32px;
            animation: bounce 2s infinite;
          }

          @keyframes pulse {

            0%,
            100% {
              transform: scale(1);
            }

            50% {
              transform: scale(1.05);
            }
          }

          @keyframes bounce {

            0%,
            20%,
            50%,
            80%,
            100% {
              transform: translateY(0);
            }

            40% {
              transform: translateY(-10px);
            }

            60% {
              transform: translateY(-5px);
            }
          }
        }
      }

      .title {
        font-size: 28px;
        font-weight: 700;
        color: @text-color;
        margin: 0 0 8px 0;
        background: linear-gradient(135deg, @primary-color, @primary-light);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }

      .subtitle {
        font-size: 16px;
        color: @text-light;
        margin: 0;
      }
    }

    // 登录表单
    .login-form {
      .input-group {
        margin-bottom: 24px;

        .input-wrapper {
          position: relative;

          .input-field {
            width: 100%;
            padding: 16px 20px 16px 50px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 16px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            outline: none;

            &:focus {
              border-color: @primary-color;
              background: @white;
              box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
            }

            &:focus+.input-label,
            &:not(:placeholder-shown)+.input-label {
              transform: translateY(-50px) scale(0.85);
              color: @primary-color;
            }
          }

          .input-label {
            position: absolute;
            left: 50px;
            top: 50%;
            transform: translateY(-50%);
            color: @text-light;
            font-size: 16px;
            transition: all 0.3s ease;
            pointer-events: none;
            display: flex;
            align-items: center;
            gap: 8px;

            .input-icon {
              font-size: 18px;
            }
          }

          .input-line {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 2px;
            background: linear-gradient(90deg, @primary-color, @primary-light);
            transition: width 0.3s ease;
          }

          .input-field:focus~.input-line {
            width: 100%;
          }

          // 验证码特殊样式
          &.captcha-wrapper {
            .captcha-input {
              padding-right: 100px;
            }

            .captcha-code {
              position: absolute;
              right: 12px;
              top: 50%;
              transform: translateY(-50%);
              width: 80px;
              height: 40px;
              background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
              border: 2px solid #d1d5db;
              border-radius: 8px;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 18px;
              font-weight: bold;
              color: @text-color;
              cursor: pointer;
              user-select: none;
              transition: all 0.3s ease;

              &:hover {
                background: linear-gradient(45deg, #e0e0e0, #d0d0d0);
                transform: translateY(-50%) scale(1.05);
              }

              &:active {
                transform: translateY(-50%) scale(0.95);
              }
            }
          }
        }
      }

      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32px;

        .register-section {
          display: flex;
          align-items: center;
          gap: 8px;

          .register-text {
            font-size: 14px;
            color: @text-light;
          }

          .register-link {
            color: @primary-color;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            padding: 4px 8px;
            border-radius: 6px;

            &:hover {
              color: @primary-dark;
              background: rgba(99, 102, 241, 0.1);
              transform: translateY(-1px);
            }
          }
        }

        .forgot-link {
          color: @primary-color;
          text-decoration: none;
          font-size: 14px;
          transition: color 0.3s ease;

          &:hover {
            color: @primary-dark;
          }
        }
      }

      .login-btn {
        width: 100%;
        padding: 16px;
        background: linear-gradient(135deg, @primary-color, @primary-light);
        border: none;
        border-radius: 12px;
        color: @white;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3);
        }

        &:active {
          transform: translateY(0);
        }

        &.loading {
          pointer-events: none;

          .btn-text {
            opacity: 0;
          }

          .btn-loader {
            opacity: 1;
          }
        }

        .btn-text {
          transition: opacity 0.3s ease;
        }

        .btn-loader {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          opacity: 0;
          transition: opacity 0.3s ease;

          .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid @white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
          }

          @keyframes spin {
            0% {
              transform: rotate(0deg);
            }

            100% {
              transform: rotate(360deg);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    justify-content: center; // 移动端居中显示

    .login-box {
      width: 90%;
      max-width: 400px;
      padding: 30px 20px;
      margin-right: 0; // 移动端去掉右边距
    }

    .welcome-text {
      display: none;
    }
  }
}
</style>